package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


import static com.sky.constant.RedisConstant.DISH_KRY;
import static com.sky.constant.StatusConstant.ENABLE;

@Service
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {
    private final DishMapper dishMapper;
    private final DishFlavorMapper dishflavorMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final StringRedisTemplate redisTemplate;


    /**
     * 分页查询菜品信息
     *
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult dishPage(DishPageQueryDTO pageQueryDTO) {
        //设置分页默认参数
        if (pageQueryDTO.getPage() == null || pageQueryDTO.getPageSize() == null) {
            pageQueryDTO.setPage(1);
            pageQueryDTO.setPageSize(10);
        }
        //开启分页
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        //进行分页查询
        Page<DishVO> page = dishMapper.dishList(pageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        //获取菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //对象拷贝
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //属性赋值
        Long currentUserId = BaseContext.getCurrentId();
        dish.setCreateUser(currentUserId);
        dish.setUpdateUser(currentUserId);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        //获取修改菜品的名字
        String name = dishDTO.getName();
        //判断菜品名称是否存在
        long count = dishMapper.selectCountDishName(name);
        if (count != 0) {
            throw new BaseException("菜品名称已存在");
        }
        //保存菜品
        dishMapper.saveDish(dish);
        //获取插入的主键id
        Long dishId = dish.getId();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(item -> item.setDishId(dishId));
            //添加菜品口味
            dishflavorMapper.saveDishFlavor(flavors);
        }
        //删除Redis缓存
        redisTemplate.delete(DISH_KRY + dishId);
    }

    /**
     * 菜品起售和停售
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //获取修改的数据
        Long categoryId = dishMapper.getDishById(id).getCategoryId();
        //删除缓存
        redisTemplate.delete(DISH_KRY + categoryId);
        //更新状态
        dishMapper.startOrStop(status, id);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = dishMapper.getDishById(id);
        //查询菜品口味
        List<DishFlavor> flavors = dishflavorMapper.selectDishFlavorByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 更新菜品信息
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        //获取菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //对象拷贝
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //属性赋值
        Long currentUserId = BaseContext.getCurrentId();
        dish.setUpdateUser(currentUserId);
        dish.setUpdateTime(LocalDateTime.now());
        //判断菜品名称是否存在
        DishVO dishVO = dishMapper.getDishById(dish.getId());
        //获取菜品名称
        String dishName = dishVO.getName();
        if (dishName.equals(dish.getName())) {
            //修改菜品信息
            dishMapper.updateDishById(dish);
        } else {
            long countDishName = dishMapper.selectCountDishName(dish.getName());
            if (countDishName != 0) {
                throw new BaseException("菜品名称已存在");
            }
            //修改菜品信息
            dishMapper.updateDishById(dish);
            //清理缓存
            redisTemplate.delete(DISH_KRY + dishDTO.getCategoryId());
        }

        //删除原有口味
        dishflavorMapper.deleteDishFlavorByDishId(dish.getId());
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(item -> item.setDishId(dish.getId()));
            //添加菜品口味
            dishflavorMapper.saveDishFlavor(flavors);
        }

    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //获取删除菜品的信息
        List<Dish> list = dishMapper.selectBatchIds(ids);
        //判断是否起售
        for (Dish dish : list) {
            if (dish.getStatus().equals(ENABLE)) {
                throw new BaseException("菜品正在售卖中，不能删除");
            }
        }
        //判断菜品受否关联套餐
        long count = setmealDishMapper.selectCountByDishIds(ids);
        if (count != 0) {
            throw new BaseException("菜品关联套餐，不能删除");
        }
        //封装删除的分类id
        ArrayList<String> redisClearKey = new ArrayList<>();
        ids.forEach(item -> {
            Long categoryId = dishMapper.getDishById(item).getCategoryId();
            redisClearKey.add(DISH_KRY + categoryId);
        });
        //删除缓存
        redisTemplate.delete(redisClearKey);
        //删除菜品
        dishMapper.deleteBatchIds(ids);
        //删除菜品口味
        dishflavorMapper.deleteDishFlavorByDishIds(ids);

    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }

    /**
     * 根据分类id查询菜品，包含口味信息
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        String key = DISH_KRY + categoryId;
        ListOperations<String, String> opsForList = redisTemplate.opsForList();
        //1.查询缓存Redis中当前分类的菜品
        List<String> dishVoJsonList = opsForList.range(key, 0, -1);
        if (CollUtil.isNotEmpty(dishVoJsonList)) {
            //2.如果缓存中存在，则直接返回
            return dishVoJsonList.stream().map(item ->
                    JSONObject.parseObject(item, DishVO.class)).collect(Collectors.toList());
        }

        //3.如果缓存中不存在，则查询数据库，并将结果存入缓存中
        List<Dish> list = list(categoryId);
        if (CollUtil.isNotEmpty(list)) {
            ArrayList<DishVO> dishVOList = new ArrayList<>();
            ArrayList<String> dishVoJSONList = new ArrayList<>();
            list.forEach(dish -> {
                DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
                //获取菜品口味
                List<DishFlavor> dishFlavorList = dishflavorMapper.listByDishId(dish.getId());
                if (CollUtil.isNotEmpty(dishFlavorList)) {
                    dishVO.setFlavors(dishFlavorList);
                }
                dishVOList.add(dishVO);
                dishVoJSONList.add(JSON.toJSONString(dishVO));
            });
            //将查询结果存入缓存中
            opsForList.leftPushAll(key, dishVoJSONList);
            return dishVOList;
        }

        return null;
    }
}
